package com.stellar.auth.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import com.stellar.auth.interceptor.LoginInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


/**
 * mvc的全局处理
 *
 * @Author Jqcc
 * @Version 1.0
 * @Data 2025/3/11
 */
@Configuration
public class GlobalConfig extends WebMvcConfigurationSupport {


    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/api-miniApp/authUser/miniAppLogin")
                .excludePathPatterns("/api-miniApp/authUser/identification")
                .excludePathPatterns("/api-admin/authUser/doLogin");
    }

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedOrigins("http://localhost:9999") // 允许的域名 网关地址
                        .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允许的请求方法
                        .allowedHeaders("Content-Type", "Authorization") // 允许的请求头
                        .allowCredentials(true); // 允许发送Cookie
            }
        };
    }

    /**
     * 自定义mappingJackson2HttpMessageConverter
     * 目前实现:空值忽略，空字段可返回
     */
    private MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
        ObjectMapper objectMapper = new ObjectMapper();
        // 用于处理实体类空异常的全局配置类
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        // 返回值有null时则不返回
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        return new MappingJackson2HttpMessageConverter(objectMapper);
    }

}
